package ru.compscicenter.databases.zaikina.common.commands.bodies;

import org.json.simple.JSONArray;
import org.json.simple.JSONValue;

import java.util.AbstractList;
import java.util.ArrayList;

public abstract class AbstractListBody<E> implements CommandBody<ArrayList<E>> {
    protected ArrayList<E> value = new ArrayList<E>();

    public ArrayList<E> getValue() {
        return value;
    }

    public ArrayList<E> getFromJsonString(String jsonString) {
        JSONArray arr = (JSONArray) JSONValue.parse(jsonString);
        for (int i = 0; i < arr.size(); ++i) {
            if (arr.get(i) != null) {
                E e = getItem(arr.get(i).toString());
                if (e != null) {
                    value.add(e);
                }
            }
        }
        return value;
    }

    protected abstract E getItem(String jsonString);

    public boolean equals(Object obj) {
        if (obj instanceof AbstractListBody) {
            AbstractListBody param = (AbstractListBody) obj;
            if (param.value.size() == value.size()) {
                for (int i = 0; i < value.size(); ++i) {
                    if (!value.get(i).equals(param.value.get(i))) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
        return super.equals(obj);
    }
}
